package com.rightsidetech.http.controller.admin.activity;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.activity.dto.request.ActActivityAuditRecordReq;
import com.rightsidetech.activity.dto.request.MtActivityBaseInfoFindReq;
import com.rightsidetech.activity.dto.request.MtActivityBaseInfoInsertReq;
import com.rightsidetech.activity.dto.request.MtActivityBaseInfoUpdateReq;
import com.rightsidetech.activity.dto.request.store.*;
import com.rightsidetech.activity.dto.response.ActActivityAuditRecordResp;
import com.rightsidetech.activity.dto.response.MtActivityBaseInfoPageResp;
import com.rightsidetech.activity.dto.response.MtActivityServiceDetailResp;
import com.rightsidetech.activity.dto.response.store.*;
import com.rightsidetech.activity.entity.*;
import com.rightsidetech.activity.service.MtActivityAppService;
import com.rightsidetech.activity.service.MtActivityService;
import com.rightsidetech.commom.base.DelReq;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.enums.StoreActivityEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.commom.utils.IKExpressionUtil;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.aspect.Token;
import com.rightsidetech.http.base.BaseController;
import com.rightsidetech.mall.dto.request.CommodityActivityPageReq;
import com.rightsidetech.mall.dto.response.CommodityPageResp;
import com.rightsidetech.mall.service.MallCommodityService;
import com.rightsidetech.system.dtos.request.IdReq;
import com.rightsidetech.system.dtos.request.RegionTreeReq;
import com.rightsidetech.system.dtos.response.SysDicDIcInfoResp;
import com.rightsidetech.system.dtos.response.SysDicDIcNameResp;
import com.rightsidetech.system.dtos.response.store.StoreNamInfoResp;
import com.rightsidetech.system.entity.SysCompanyArea;
import com.rightsidetech.system.entity.SysDic;
import com.rightsidetech.system.entity.store.SysStoreInfo;
import com.rightsidetech.system.service.StoreLoginInfoService;
import com.rightsidetech.system.service.SysCompanyAreaService;
import com.rightsidetech.system.service.SysDicService;
import com.rightsidetech.system.service.SysStoreInfoService;
import com.rightsidetech.trade.dtos.response.TdUserOrderInfoResp;
import com.rightsidetech.trade.service.TdCommodityUserOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: yhr
 * @Date: 2022-02-08 17:04
 */

@RestController
@RequestMapping("/admin/mt_activity")
@ShenyuSpringMvcClient(path = "/admin/mt_activity/**")
@Api(tags = "admin:门店活动相关")
public class MtActivityController extends BaseController {
    @Resource
    private MtActivityService mtActivityService;
    @Resource
    private SysDicService sysDicService;
    @Resource
    private SysCompanyAreaService sysCompanyAreaService;
    @Resource
    private StoreLoginInfoService storeLoginInfoService;
    @Resource
    private MtActivityAppService mtActivityAppService;
    @Resource
    private TdCommodityUserOrderService tdCommodityUserOrderService;
    @Resource
    private MallCommodityService mallCommodityService;
    @Resource
    private SysStoreInfoService sysStoreInfoService;


    @Token
    @Log
    @GetMapping("/mtPage")
    @ApiOperation("门店活动列表")
    //@Auth(bizType = Auth.OPERATOR)
    public ResponseData<PageInfo<MtActivityServicePageResp>> page(MtActivityServicePageReq req) {
        return mtActivityService.page(req);
    }

    @Token
    @Log
    @GetMapping("/parentRule")
    @ApiOperation("规则大类")
    //@Auth(bizType = Auth.OPERATOR)
    public ResponseData<List<SysDicDIcNameResp>> parentRule() {
        return sysDicService.parentRule();
    }

    @Token
    @Log
    @GetMapping("/ruleList")
    @ApiOperation("规则下拉")
    //@Auth(bizType = Auth.OPERATOR)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dicType", value = "规则类型", required = true)})
    public ResponseData<List<SysDicDIcNameResp>> parentRuleList(String dicType) {
        return sysDicService.parentRuleList(dicType);
    }

    @Token
    @Log
    @GetMapping("/parentRuleInfo")
    @ApiOperation("规则大类详情")
    //@Auth(bizType = Auth.OPERATOR)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dicId", value = "规则id", required = true)})
    public ResponseData<List<SysDicDIcInfoResp>> parentRuleInfo(Long dicId) {
        return sysDicService.parentRuleInfo(dicId);
    }

    @Token
    @Log
    @GetMapping("/JFRuleInfo")
    @ApiOperation("奖励规格-积分")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dicId", value = "规则id", required = true)})
    public ResponseData<List<SysDicDIcInfoResp>> jFParentRuleInfo(Long dicId) {
        return sysDicService.jFParentRuleInfo(dicId);
    }


    @Token
    @Log
    @GetMapping("/activityInfo")
    @ApiOperation("活动详情")
    //@Auth(bizType = Auth.OPERATOR)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "activityId", value = "活动id", required = true)})
    public ResponseData<MtActivityServiceDetailResp> activityInfo(Long activityId) {
        return mtActivityService.activityInfo(activityId);
    }

    @Token
    @Log
    @GetMapping("/joinDetails")
    @ApiOperation("门店活动明细详情")
    //@Auth(bizType = Auth.OPERATOR)
    public ResponseData joinDetails(MtActivityActStoreIdReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        MtActivityRule rule = mtActivityService.selectRule(req.getActivityId(), StoreActivityEnum.HJ000.getDicType());
        if (ObjectUtils.isEmpty(rule)) {
            return ResponseData.fail("未找到活动类型");
        }
        if (!StringUtils.isEmpty(req.getRewardWay()) && "4".equals(req.getRewardWay())) {
            return mtActivityService.findMtUserJoinActivityProcess(req);
        }

        PageInfo<TdUserOrderInfoResp> tdUserOrderInfoResp = new PageInfo<>();
        if (rule.getExpressionField().equals(StoreActivityEnum.HJ001.getDicCode()) || rule.getExpressionField().equals(StoreActivityEnum.HJ004.getDicCode())) {
            PageInfo<Long> list = mtActivityService.selectBizId(req);
            tdUserOrderInfoResp.setTotal(list.getTotal());
            tdUserOrderInfoResp.setPageNum(list.getPageNum());
            tdUserOrderInfoResp.setPageSize(list.getPageSize());
            tdUserOrderInfoResp.setPages(list.getPages());
            tdUserOrderInfoResp.setList(new ArrayList<>());
            for (Long id : list.getList()) {
                tdUserOrderInfoResp.getList().add(tdCommodityUserOrderService.selectOrderById(id));
            }
            return ResponseData.success(tdUserOrderInfoResp);
        } else if (rule.getExpressionField().equals(StoreActivityEnum.HJ003.getDicCode()) || rule.getExpressionField().equals(StoreActivityEnum.HJ002.getDicCode())) {
            List<MtAwardImgResp> resp = mtActivityService.selectImgBizId(req.getActivityId(), req.getStoreId());
            return ResponseData.success(resp);
        }
        return ResponseData.success();
    }


    @Token
    @Log
    @PostMapping("/del")
    @ApiOperation("删除活动")
    @Transactional
    //@Auth(bizType = Auth.OPERATOR)
    public ResponseData delActivity(@RequestBody DelReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        return ResponseData.success(mtActivityService.delActivity(req.getId()));
    }

    @Token
    @Log
    //@Auth(bizType = Auth.OPERATOR)
    @GetMapping("/activityInfoPage")
    @ApiOperation("门店活动明细")
    public ResponseData<PageInfo<MtActivityServiceInfoPageResp>> activityInfoPage(MtActivityServiceInfoPageReq req) {
        ResponseData<PageInfo<MtActivityServiceInfoPageResp>> responseData = mtActivityService.activityInfoPage(req);
        if (responseData.getCodeId() == 1) {
            for (MtActivityServiceInfoPageResp resp : responseData.getResData().getList()) {
                StoreNamInfoResp storeInfo = storeLoginInfoService.selectName(resp.getStoreId());
                resp.setStoreName(storeInfo.getStoreName());
            }
        }
        return responseData;
    }

    @Token
    @Log
    //@Auth(bizType = Auth.OPERATOR)
    @GetMapping("/activityEndPage")
    @ApiOperation("活动结果列表")
    public ResponseData<PageInfo<MtActivityEndPageResp>> activityEndPage(MtActivityEndPageReq req) {
        PageInfo<MtActivityEndPageResp> pageInfo = mtActivityService.activityEndPage(req);
        //计算属于这些代理商下的门店数量
        List<MtActivityEndPageResp> pages = pageInfo.getList();

        if (!CollectionUtils.isEmpty(pages)) {
            for (MtActivityEndPageResp resp : pages) {
                // todo 查询活动所有规则
                List<MtActivityRule> ruleList = mtActivityService.selectRuleAll(resp.getActId(), null);
                if (!CollectionUtils.isEmpty(ruleList)) {
                    for (MtActivityRule rule : ruleList) {
                        if (StoreActivityEnum.HJ001.getDicType().equals(rule.getMold())) {
                            resp.setAwardRule(rule.getExpressionField());
                            resp.setActivityRule(rule.getConditions());
                            if (StoreActivityEnum.HJ001.getDicCode().equals(resp.getAwardRule())) {
                                resp.setAwardRule(StoreActivityEnum.HJ001.getDicValue());
                            }
                            if (StoreActivityEnum.HJ002.getDicCode().equals(resp.getAwardRule())) {
                                resp.setAwardRule(StoreActivityEnum.HJ002.getDicValue());
                            }
                            if (StoreActivityEnum.HJ003.getDicCode().equals(resp.getAwardRule())) {
                                resp.setAwardRule(StoreActivityEnum.HJ003.getDicValue());
                            }
                            if (StoreActivityEnum.HJ004.getDicCode().equals(resp.getAwardRule())) {
                                resp.setAwardRule(StoreActivityEnum.HJ004.getDicValue());
                            }
                        }
                        if (StoreActivityEnum.JF001.getDicType().equals(rule.getMold())) {
                            resp.setRewardWay(rule.getExpressionField());
                            if (StoreActivityEnum.JF001.getDicCode().equals(resp.getRewardWay())) {
                                resp.setRewardWay(StoreActivityEnum.JF001.getDicValue());
                            }
                            if (StoreActivityEnum.JF002.getDicCode().equals(resp.getRewardWay())) {
                                resp.setRewardWay(StoreActivityEnum.JF002.getDicValue());
                            }
                            if (StoreActivityEnum.JF003.getDicCode().equals(resp.getRewardWay())) {
                                resp.setRewardWay(StoreActivityEnum.JF003.getDicValue());
                            }
                            if (StoreActivityEnum.JF004.getDicCode().equals(resp.getRewardWay())) {
                                resp.setRewardWay(StoreActivityEnum.JF004.getDicValue());
                            }
                        }
                        if (StoreActivityEnum.PB001.getDicType().equals(rule.getMold())) {
                            resp.setCompare(rule.getExpressionField());
                            if (StoreActivityEnum.PB001.getDicCode().equals(resp.getCompare())) {
                                resp.setCompare(StoreActivityEnum.PB001.getDicValue());
                            }
                            if (StoreActivityEnum.PB002.getDicCode().equals(resp.getCompare())) {
                                resp.setCompare(StoreActivityEnum.PB002.getDicValue());
                            }
                        }
                        if (StoreActivityEnum.CY001.getDicCode().equals(rule.getExpressionField())) {
                            resp.setEstimateNum(rule.getExpression());
                        }
                        if (StoreActivityEnum.ZE001.getDicType().equals(rule.getMold())) {
                            resp.setReward(Long.parseLong(rule.getConditionValue()));
                        }
                        if (StoreActivityEnum.JL000.getDicType().equals(rule.getMold())) {
                            if (rule.getExpressionField().equals(StoreActivityEnum.JL001.getDicCode())) {
                                resp.setAmountType((byte) 1);
                            } else {
                                resp.setAmountType((byte) 2);
                            }
                        }
                    }
                }

                if (!StringUtils.isEmpty(resp.getEstimateNum()) && !"[]".equals(resp.getEstimateNum())) {
//                String ids = pageResp.getEstimateNum().substring(0,pageResp.getEstimateNum().length()-1).replace(" ","");
                    String ids = resp.getEstimateNum().replace("[", "").replace("]", "");
                    String[] split = ids.split(",");
                    List<String> agentIds = Arrays.asList(split);
                    resp.setEstimateNum(String.valueOf(agentIds.size()));
                    resp.setAgentIds(agentIds);
                } else {
                    resp.setEstimateNum(String.valueOf(0));
                }

                if (!StringUtils.isEmpty(resp.getAgentIds())) {
                    List<String> agentIds = resp.getAgentIds();
                    List<Long> agentIds2 = agentIds.stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
                    List<Long> storeIds = sysStoreInfoService.selectIdsByAgentIds(agentIds2);
                    resp.setEstimateNum(String.valueOf(storeIds.size()));
                    resp.setAgentIds(null);
                }


                resp.setActivityTime(resp.getStartTime() + "至" + resp.getEndTime());

                if (StringUtils.isEmpty(resp.getActualReward())) {
                    resp.setActualReward((long) 0);
                }
                if (StringUtils.isEmpty(resp.getReward())) {
                    resp.setReward((long) 0);
                }


                if (!StringUtils.isEmpty(resp.getRewardWay()) && "4".equals(resp.getRewardWay())) {
//                    //抽奖金额单独计算
//                    List<MtActivityRule> rules = mtActivityService.selectRuleAll(resp.getActId(), StoreActivityEnum.GS001.getDicType());
//                    BigDecimal total = BigDecimal.ZERO;
//                    if (!CollectionUtils.isEmpty(rules)){
//                        for (MtActivityRule rule:rules){
//                            BigDecimal multiply = new BigDecimal(rule.getConditions()).multiply(new BigDecimal(rule.getExpression()));
//                            total = total.add(multiply);
//                        }
//                    }
                    resp.setReward(resp.getActualReward());
//                    resp.setActualReward();
                }

                List<MtUserJoinActivityApply> applyList = mtActivityService.selectApplyByActId(resp.getActId());
                if (CollectionUtils.isEmpty(applyList)) {
                    resp.setActualNum(0L);
                    resp.setAwardNum(0L);
                }
                List<MtUserJoinActivityApply> collect = applyList.stream().filter(MtUserJoinActivityApply ->
                        MtUserJoinActivityApply.getStatus() == 1 || MtUserJoinActivityApply.getStatus() == 3).collect(Collectors.toList());
                resp.setActualNum((long) applyList.size());
                resp.setAwardNum((long) collect.size());
            }
        }

        return ResponseData.success(pageInfo);
    }

    @Token
    @Log
    //@Auth(bizType = Auth.OPERATOR)
    @GetMapping("/activityEndInfoPage")
    @ApiOperation("活动结果")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "activityId", value = "活动id", required = true)})
    public ResponseData<PageInfo<MtActivityEndInfoResp>> activityEndInfoPage(MtActivityActIdReq req) {
        List<Long> areaIds = null;
        MtActivityRule rule = mtActivityService.selectRule(req.getActivityId(), StoreActivityEnum.PB000.getDicType());
        if (!ObjectUtils.isEmpty(rule)) {
            areaIds = sysCompanyAreaService.allAreaId();
        }
        //判断是否是抽奖活动
        boolean isCJ = false;
        MtActivityRule cjRule = mtActivityService.selectRule(req.getActivityId(), StoreActivityEnum.CJ002.getDicType());
        if (!ObjectUtils.isEmpty(cjRule) && cjRule.getExpressionField().equals(StoreActivityEnum.CJ002.getDicCode())) {
            isCJ = true;
        }

        ResponseData<PageInfo<MtActivityEndInfoResp>> pageInfoResponseData = mtActivityService.activityEndInfoPage(req, areaIds, rule);
        if (pageInfoResponseData.getCodeId() == 1) {
            PageInfo<MtActivityEndInfoResp> resData = pageInfoResponseData.getResData();
            List<MtActivityEndInfoResp> list = resData.getList();
            if (!CollectionUtils.isEmpty(list)) {
                for (MtActivityEndInfoResp resp : list) {
                    SysStoreInfo sysStoreInfo = sysStoreInfoService.selectByPrimaryKey(resp.getStoreId());
                    if (!ObjectUtils.isEmpty(sysStoreInfo)) {
                        resp.setStoreBoss(sysStoreInfo.getStoreBoss());
                        resp.setAddress(sysStoreInfo.getAdress() +
                                (StringUtils.isEmpty(sysStoreInfo.getDoorplate()) ? "" : sysStoreInfo.getDoorplate()));
                        SysCompanyArea sysCompanyArea = sysCompanyAreaService.selectById(sysStoreInfo.getAreaId());
                        if (!ObjectUtils.isEmpty(sysCompanyArea)) {
                            resp.setAreaName(sysCompanyArea.getName());
                        }
                    }
                    if (isCJ && !StringUtils.isEmpty(resp.getReward())) {
//                        resp.setReward(new BigDecimal(resp.getReward()).multiply(new BigDecimal(100)).toString());
                        MtActivityRule awardRule = mtActivityService.selectRule(req.getActivityId(), StoreActivityEnum.HJ004.getDicType());
                        if (!ObjectUtils.isEmpty(awardRule)) {
                            resp.setCountNum(resp.getCountNum() / Long.parseLong(awardRule.getConditionValue()));
                        }
                    }

                }
            }
        }
        return pageInfoResponseData;
    }


    @Token
    @Log
    @GetMapping("/activityEndInfo")
    @ApiOperation("活动结果详情")
    //@Auth(bizType = Auth.OPERATOR)
    public ResponseData activityEndInfo(MtActivityActStoreIdReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        MtActivityRule rule = mtActivityService.selectRule(req.getActivityId(), StoreActivityEnum.HJ000.getDicType());
        if (ObjectUtils.isEmpty(rule)) {
            return ResponseData.fail("未找到活动类型");
        }
        if (!StringUtils.isEmpty(req.getRewardWay()) && "4".equals(req.getRewardWay())) {
            return mtActivityService.findMtUserJoinActivityProcess(req);
        }


        MtActivityRule ruleCj = mtActivityAppService.selectRuleByFieldAndActId(req.getActivityId(), StoreActivityEnum.CJ001.getDicCode());
        if (!ObjectUtils.isEmpty(ruleCj)) {
            PageInfo<MtActivityLuckInfoResp> respPageInfo = mtActivityAppService.selectLuckResp(req);
            for (MtActivityLuckInfoResp resp : respPageInfo.getList()) {
                TdUserOrderInfoResp orderInfoResp = tdCommodityUserOrderService.selectOrderById(Long.valueOf(resp.getBizId()));
                if (!ObjectUtils.isEmpty(orderInfoResp)) {
                    resp.setOrderNo(orderInfoResp.getOrderNo());
                    resp.setStatus(String.valueOf(orderInfoResp.getStatus()));
                    resp.setCommName(orderInfoResp.getCommName());
                }
            }
            return ResponseData.success(respPageInfo);
        }
        PageInfo<TdUserOrderInfoResp> tdUserOrderInfoResp = new PageInfo<>();
        if (rule.getExpressionField().equals(StoreActivityEnum.HJ001.getDicCode()) || rule.getExpressionField().equals(StoreActivityEnum.HJ004.getDicCode())) {

            PageInfo<Long> list = mtActivityService.selectBizId(req);
            if (!ObjectUtils.isEmpty(list.getList())) {
                tdUserOrderInfoResp.setTotal(list.getTotal());
                tdUserOrderInfoResp.setPageNum(list.getPageNum());
                tdUserOrderInfoResp.setPageSize(list.getPageSize());
                tdUserOrderInfoResp.setPages(list.getPages());
                tdUserOrderInfoResp.setList(new ArrayList<>());
                for (Long id : list.getList()) {
                    tdUserOrderInfoResp.getList().add(tdCommodityUserOrderService.selectOrderById(id));
                }
                return ResponseData.success(tdUserOrderInfoResp);
            }
        } else if (rule.getExpressionField().equals(StoreActivityEnum.HJ003.getDicCode()) || rule.getExpressionField().equals(StoreActivityEnum.HJ002.getDicCode())) {
            List<MtAwardImgResp> resp = mtActivityService.selectImgBizId(req.getActivityId(), req.getStoreId());
            return ResponseData.success(resp);
        }
        return ResponseData.success();
    }

    @Token
    @Log
    @PostMapping("/payment")
    @ApiOperation("一键打款(现未做真实打款)")
    //@Auth(bizType = Auth.OPERATOR)
    public ResponseData payment(@RequestBody IdReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        MtActivityRule rule = mtActivityService.selectRule(req.getId(), StoreActivityEnum.HJ000.getDicType());
        if (ObjectUtils.isEmpty(rule)) {
            return ResponseData.fail("未找到活动类型");
        }
        MtActivityRule paymentRule = mtActivityService.selectRule(req.getId(), StoreActivityEnum.DK000.getDicType());
        if (ObjectUtils.isEmpty(paymentRule)) {
            return ResponseData.fail("未找到打款规则");
        }
        if (!paymentRule.getExpressionField().equals(StoreActivityEnum.DK001.getDicCode())) {
            return ResponseData.fail("该活动为自动打款,无需手动");
        }

        //查询活动结果
        List<Long> areaIds = null;
        MtActivityRule rule2 = mtActivityService.selectRule(req.getId(), StoreActivityEnum.PB000.getDicType());
        if (!ObjectUtils.isEmpty(rule2)) {
            areaIds = sysCompanyAreaService.allAreaId();
        }
        Long loginId = Long.valueOf(getAttribute());
        String loginName = getLoginName();

        return mtActivityService.activityPayment(req.getId(), areaIds, rule2, loginId, loginName);
    }


    @Token
    @Log
    @PostMapping("/verifyImg")
    @ApiOperation("审核堆头/集赞活动")
    //@Auth(bizType = Auth.OPERATOR)
    public ResponseData verifyImg(@RequestBody MtActivityVerifyImgReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        if (req.getStatus() == 2) {
            if (StringUtils.isEmpty(req.getRejectReason())) {
                return ResponseData.fail("驳回原因不能为空");
            }
        }

        Long loginInfoId = Long.parseLong(getAttribute());
        String loginName = getLoginName();

        mtActivityService.verifyImg(req, loginInfoId, loginName);
        return ResponseData.success();
    }



    @Token
    @Log
    @PostMapping("/verify")
    @ApiOperation("审核新建活动")
    //@Auth(bizType = Auth.OPERATOR)
    public ResponseData verify(@RequestBody MtActivityVerifyReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        MtActivity mtActivity = mtActivityService.selectById(req.getActId());
        if (ObjectUtils.isEmpty(mtActivity)) {
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        if (req.getStatus() == 2) {
            if (StringUtils.isEmpty(req.getRejectReason())) {
                return ResponseData.fail("驳回原因不能为空");
            }
        }
        ResponseData responseData = mtActivityService.verify(req);
        if (responseData.getCodeId() == 1 && req.getStatus() == 1) {
            MtActivityRule rule = mtActivityService.selectByActId(req.getActId(), StoreActivityEnum.BM000.getDicType());
            if (ObjectUtils.isEmpty(rule)) {
                return responseData;
            }
            if (rule.getExpressionField().equals(StoreActivityEnum.BM002.getDicCode())) {
                MtActivityRule activityRule = mtActivityService.selectByActId(req.getActId(), StoreActivityEnum.CY000.getDicType());
                if (ObjectUtils.isEmpty(activityRule)) {
                    return responseData;
                }
                if (activityRule.getExpressionField().equals(StoreActivityEnum.CY001.getDicCode())) {
                    List<Long> agentIds = JSONUtil.toList(activityRule.getExpression(), Long.class);
                    List<SysStoreInfo> list = sysStoreInfoService.selectBaseByAgentIds(agentIds);
                    for (SysStoreInfo info : list) {
                        MtUserJoinActivityApply apply = new MtUserJoinActivityApply();
                        apply.setActId(req.getActId());
                        apply.setActName(mtActivity.getName());
                        apply.setActStart(mtActivity.getStartTime());
                        apply.setActEnd(mtActivity.getEndTime());
                        apply.setUserAccountId(info.getId());
                        apply.setUserLoginName(info.getStoreName());
                        apply.setUserPhone(info.getConnectWay());
                        apply.setJoinTime(new Date());
                        apply.setStatus((short) 0);
                        mtActivityAppService.insertUserJoin(apply);
                    }
                } else if (activityRule.getExpressionField().equals(StoreActivityEnum.CY002.getDicCode())) {
                    //按等级规则

                }
            }
        }
        //添加审核记录
        Long loginInfoId = Long.parseLong(getAttribute());
        String loginName = getLoginName();
        if (null == loginInfoId || null == loginName){
            return ResponseData.fail("未找到当前登录人");
        }
        ActActivityAuditRecord activityAuditRecord = new ActActivityAuditRecord();
        activityAuditRecord.setActivityId(req.getActId());
        if(req.getStatus() == 2){
            activityAuditRecord.setAuditStatus((byte) 1);
        }else{
            activityAuditRecord.setAuditStatus((byte) -1);
        }
        activityAuditRecord.setAuditContent(req.getRejectReason());
        activityAuditRecord.setCreatedName(loginName);
        activityAuditRecord.setCreatedAt(new Date());
        activityAuditRecord.setCreaterId(loginInfoId);
        activityAuditRecord.setActivityName("门店活动");
        activityAuditRecord.setEventName(mtActivity.getName());
        mtActivityService.insertAtActivity(activityAuditRecord);
        return responseData;
    }

    @Token
    @Log
    @PostMapping("/saveActivityRule")
    @ApiOperation("新建活动")
    @Transactional
    //@Auth(bizType = Auth.OPERATOR)
    public ResponseData saveActivityRule(@RequestBody MtActivityServiceUpdateReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long loginInfoId = Long.parseLong(getAttribute());
        String loginName = getLoginName();
        if (null == loginInfoId || null == loginName) {
            return ResponseData.fail("未找到登录人");
        }

        //判断基础活动模版不存在
        MtActivityBaseInfo mtActivityBaseInfo = mtActivityService.findActivityBaseInfo(req.getActivityBaseInfoId());
        if(StringUtils.isEmpty(mtActivityBaseInfo)){
            return ResponseData.fail("基础活动模板不存在");
        }

        saveNewActivityRule(req, (byte) 1, loginInfoId, loginName);
        return ResponseData.success();
    }

    @Log
    //@Auth(bizType = Auth.OPERATOR)
    @Token
    @GetMapping("/page")
    @ApiOperation("分页查询商品列表")
    public ResponseData<List<CommodityPageResp>> selectPage(CommodityActivityPageReq req) {
        return mallCommodityService.selectActivityPageList(req);
    }

    @Token
    @Log
    @PostMapping("/updateActivityRule")
    @ApiOperation("修改活动")
    @Transactional
    //@Auth(bizType = Auth.OPERATOR)
    public ResponseData updateActivityRule(@RequestBody MtActivityServiceUpdateReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        Long loginInfoId = Long.parseLong(getAttribute());
        String loginName = getLoginName();
        if (null == loginInfoId || null == loginName) {
            return ResponseData.fail("未找到登录人");
        }

        //判断基础活动模版不存在
        MtActivityBaseInfo mtActivityBaseInfo = mtActivityService.findActivityBaseInfo(req.getActivityBaseInfoId());
        if(StringUtils.isEmpty(mtActivityBaseInfo)){
            return ResponseData.fail("基础活动模板不存在");
        }

        MtActivity mtActivity2 = mtActivityService.selectById(req.getActId());
        if (StringUtils.isEmpty(mtActivity2)) {
            return ResponseData.fail("找不到该活动");
        }
        mtActivityService.delRule(req.getActId());
        saveNewActivityRule(req, (byte) 2, loginInfoId, loginName);
        return ResponseData.success();
    }

    private void saveNewActivityRule(MtActivityServiceUpdateReq req, Byte type, Long sysLoginId, String sysUserLoginName) {
        Long actId = null;
        if (type == 1) {
            MtActivity mtActivity = new MtActivity();
            mtActivity.setName(req.getActivityName());
            //mtActivity.setDescribes(req.getActivityDesc());
            mtActivity.setThemePic(req.getThemePic());
            mtActivity.setPosterPic(req.getPosterPic());
            mtActivity.setStartTime(req.getStartTime());
            mtActivity.setEndTime(req.getEndTime());
            mtActivity.setCreatedAt(new Date());
            mtActivity.setCreaterName(sysUserLoginName);
            mtActivity.setCreaterId(sysLoginId);
            mtActivity.setBackgroundPic(req.getBackgroundPic());
            mtActivity.setActivityBaseInfoId(req.getActivityBaseInfoId());
            actId = mtActivityService.saveMtActivity(mtActivity);

            MtActivityRuleDetailWithBLOBs bloBs = new MtActivityRuleDetailWithBLOBs();
            bloBs.setActId(actId);
            bloBs.setReqValues(JSONObject.toJSONString(req));
            bloBs.setRuleDetail(req.getRuleDetails());
            bloBs.setActUrl(req.getActUrl());
            mtActivityService.saveMtActivityRuleDetail(bloBs);
        } else {
            MtActivity mtActivity2 = mtActivityService.selectById(req.getActId());
            actId = req.getActId();
            MtActivity mtActivity = new MtActivity();
            mtActivity.setId(req.getActId());
            mtActivity.setName(req.getActivityName());
            //mtActivity.setDescribes(req.getActivityDesc());
            mtActivity.setThemePic(req.getThemePic());
            mtActivity.setPosterPic(req.getPosterPic());
            mtActivity.setStartTime(req.getStartTime());
            mtActivity.setEndTime(req.getEndTime());
            mtActivity.setUpdatedAt(new Date());
            if (mtActivity2.getStatus() == 2) {
                mtActivity.setStatus((short) 0);
            }
            mtActivity.setUpdaterId(sysLoginId);
            mtActivity.setUpdaterName(sysUserLoginName);
            mtActivity.setBackgroundPic(req.getBackgroundPic());
            mtActivity.setActivityBaseInfoId(req.getActivityBaseInfoId());
            mtActivityService.updateMtActivity(mtActivity);

            MtActivityRuleDetailWithBLOBs bloBs = new MtActivityRuleDetailWithBLOBs();
            bloBs.setActId(actId);
            bloBs.setReqValues(JSONObject.toJSONString(req));
            bloBs.setRuleDetail(req.getRuleDetails());
            bloBs.setUpdatedAt(new Date());
            bloBs.setActUrl(req.getActUrl());
            mtActivityService.updateMtActivityRuleDetail(bloBs);
        }

        if (!ObjectUtils.isEmpty(req.getJoinRule())) {
            //参加规则（1区域 2等级）
            if (req.getJoinRule().equals(StoreActivityEnum.CY001.getDicValue())) {
                SysDic joinResp = sysDicService.selectRuleByCode(StoreActivityEnum.CY001.getDicCode());
                List<Long> ids = getAgentIds(req.getAreasIds(), req.getAgentIds());
                saveRule(actId, joinResp, ids.toString(), null);

                //保存活动代理商/大区 关联
                //mtActivityService.activityRelation(acdId,req.getAreasIds().toString(),req.getAreasIds().toString());
            } else {
                SysDic joinResp = sysDicService.selectRuleByCode(StoreActivityEnum.CY002.getDicCode());
                saveRule(actId, joinResp, ">=" + req.getLevel(), req.getLevel());
            }
            //报名方式（1手动 2自动）
            SysDic enrollResp = null;
            if (req.getEnroll().equals(StoreActivityEnum.BM001.getDicValue())) {
                enrollResp = sysDicService.selectRuleByCode(StoreActivityEnum.BM001.getDicCode());
            } else {
                enrollResp = sysDicService.selectRuleByCode(StoreActivityEnum.BM002.getDicCode());
            }
            if (!ObjectUtils.isEmpty(enrollResp)) {
                SysDic enrollStartTime = sysDicService.selectRuleByCode(StoreActivityEnum.SB001.getDicCode());
                SysDic enrollEndTime = sysDicService.selectRuleByCode(StoreActivityEnum.SB002.getDicCode());

                saveRule(actId, enrollStartTime, ">=[" + req.getEnrollStartTime() + "]", req.getEnrollStartTime());
                saveRule(actId, enrollEndTime, "<=[" + req.getEnrollEndTime() + "]", req.getEnrollEndTime());
                saveRule(actId, enrollResp, null, null);
            }
        }

        //获奖标准
        SysDic awardResp = null;
        if (!StringUtils.isEmpty(req.getAwardRule())) {
            if (req.getAwardRule().equals(StoreActivityEnum.HJ001.getDicValue())) {
                awardResp = sysDicService.selectRuleByCode(StoreActivityEnum.HJ001.getDicCode());
            } else if (req.getAwardRule().equals(StoreActivityEnum.HJ002.getDicValue())) {
                awardResp = sysDicService.selectRuleByCode(StoreActivityEnum.HJ002.getDicCode());
                //上传集赞图片
                saveBusiness(type, actId, req.getActivityName(), req.getImages());
            } else if (req.getAwardRule().equals(StoreActivityEnum.HJ003.getDicValue())) {
                awardResp = sysDicService.selectRuleByCode(StoreActivityEnum.HJ003.getDicCode());
            } else if (req.getAwardRule().equals(StoreActivityEnum.HJ004.getDicValue())) {
                awardResp = sysDicService.selectRuleByCode(StoreActivityEnum.HJ004.getDicCode());
                //商品id
                saveBusiness(type, actId, req.getActivityName(), req.getCommIds());
            }
            if (!ObjectUtils.isEmpty(awardResp)) {
                saveRule(actId, awardResp, ">=" + req.getQuantity(), req.getQuantity());
            }
        }

        //排名活动
        SysDic compare = null;
        if (!StringUtils.isEmpty(req.getCompare())) {
            if (req.getCompare().equals(StoreActivityEnum.PB001.getDicValue())) {
                compare = sysDicService.selectRuleByCode(StoreActivityEnum.PB001.getDicCode());
                saveRule(actId, compare, req.getCompareNum(), req.getCompareNum());
            }
            if (req.getCompare().equals(StoreActivityEnum.PB002.getDicValue())) {
                compare = sysDicService.selectRuleByCode(StoreActivityEnum.PB002.getDicCode());
                saveRule(actId, compare, req.getCompareNum(), req.getCompareNum());
            }
        }

        //奖励规则（1现金 2积分）
        SysDic rewardResp = null;
        if (!StringUtils.isEmpty(req.getReward())) {
            if (req.getReward().equals(StoreActivityEnum.JL001.getDicValue())) {
                rewardResp = sysDicService.selectRuleByCode(StoreActivityEnum.JL001.getDicCode());
            } else {
                rewardResp = sysDicService.selectRuleByCode(StoreActivityEnum.JL002.getDicCode());
            }
            if (!ObjectUtils.isEmpty(rewardResp)) {
                saveRule(actId, rewardResp, null, null);
            }
        }

        //奖励方式（1平分 2随机 3固定 4固定随机）
        SysDic rewardWayResp = null;
        if (!StringUtils.isEmpty(req.getReward())) {
            if (req.getRewardWay().equals(StoreActivityEnum.JF001.getDicValue())) {
                rewardWayResp = sysDicService.selectRuleByCode(StoreActivityEnum.JF001.getDicCode());
                SysDic totalAmountResp = sysDicService.selectRuleByCode(StoreActivityEnum.ZE001.getDicCode());

                saveRule(actId, totalAmountResp, req.getCountAmount(), req.getCountAmount());
            } else if (req.getRewardWay().equals(StoreActivityEnum.JF002.getDicValue())) {
                rewardWayResp = sysDicService.selectRuleByCode(StoreActivityEnum.JF002.getDicCode());
                SysDic totalAmountResp = sysDicService.selectRuleByCode(StoreActivityEnum.ZE001.getDicCode());

                saveRule(actId, totalAmountResp, req.getCountAmount(), req.getCountAmount());
            } else if (req.getRewardWay().equals(StoreActivityEnum.JF003.getDicValue())) {
                rewardWayResp = sysDicService.selectRuleByCode(StoreActivityEnum.JF003.getDicCode());
                SysDic count = sysDicService.selectRuleByCode(StoreActivityEnum.ZE001.getDicCode());

                saveRule(actId, count, req.getCountAmount(), req.getCountAmount());
            } else if (req.getRewardWay().equals(StoreActivityEnum.JF004.getDicValue())) {
                rewardWayResp = sysDicService.selectRuleByCode(StoreActivityEnum.JF004.getDicCode());
                SysDic oneNum = sysDicService.selectRuleByCode(StoreActivityEnum.GS001.getDicCode());
                SysDic twoNum = sysDicService.selectRuleByCode(StoreActivityEnum.GS002.getDicCode());
                SysDic threeNum = sysDicService.selectRuleByCode(StoreActivityEnum.GS003.getDicCode());

                saveRule(actId, oneNum, req.getOneNum(), req.getOneNum());
                saveRule(actId, twoNum, req.getTwoNum(), req.getTwoNum());
                saveRule(actId, threeNum, req.getThreeNum(), req.getThreeNum());
            }
            if (!ObjectUtils.isEmpty(rewardWayResp)) {
                saveRule(actId, rewardWayResp, null, null);
            }
        }

        //参与方式(1区域 2等级)
        SysDic attend = null;
        if (!StringUtils.isEmpty(req.getAttend())) {
            if (req.getAttend().equals(StoreActivityEnum.CJ001.getDicValue())) {
                attend = sysDicService.selectRuleByCode(StoreActivityEnum.CJ001.getDicCode());
            } else if (req.getAttend().equals(StoreActivityEnum.CJ002.getDicValue())) {
                attend = sysDicService.selectRuleByCode(StoreActivityEnum.CJ002.getDicCode());
            } else {
                attend = sysDicService.selectRuleByCode(StoreActivityEnum.CJ003.getDicCode());
            }
            saveRule(actId, attend, null, null);
        }

        //打款方式（1手动 2自动）
        SysDic paymentResp = null;
        if (!StringUtils.isEmpty(req.getPayment())) {
            if (req.getPayment().equals(StoreActivityEnum.DK001.getDicValue())) {
                paymentResp = sysDicService.selectRuleByCode(StoreActivityEnum.DK001.getDicCode());
            } else {
                paymentResp = sysDicService.selectRuleByCode(StoreActivityEnum.DK001.getDicCode());
            }
            if (!ObjectUtils.isEmpty(paymentResp)) {
                saveRule(actId, paymentResp, null, null);
            }
        }

        //领奖开始时间
        if (!ObjectUtils.isEmpty(req.getRewardStartTime())) {
            SysDic rewardStartTimeResp = sysDicService.selectRuleByCode(StoreActivityEnum.LT001.getDicCode());
            saveRule(actId, rewardStartTimeResp, ">=[" + req.getRewardStartTime() + "]", req.getRewardStartTime());
        }
        //领奖结束时间
        if (!ObjectUtils.isEmpty(req.getRewardEndTime())) {
            SysDic rewardEndTimeCodeResp = sysDicService.selectRuleByCode(StoreActivityEnum.LT002.getDicCode());
            saveRule(actId, rewardEndTimeCodeResp, "<=[" + req.getRewardEndTime() + "]", req.getRewardEndTime());
        }

        //模板
        SysDic posterPicCodeResp = null;
        if (!StringUtils.isEmpty(req.getPosterPicName())) {
            if (req.getPosterPicName().equals(StoreActivityEnum.MB001.getDicValue())) {
                posterPicCodeResp = sysDicService.selectRuleByCode(StoreActivityEnum.MB001.getDicCode());
            } else if (req.getPosterPicName().equals(StoreActivityEnum.MB002.getDicValue())) {
                posterPicCodeResp = sysDicService.selectRuleByCode(StoreActivityEnum.MB002.getDicCode());
            } else if (req.getPosterPicName().equals(StoreActivityEnum.MB003.getDicValue())) {
                posterPicCodeResp = sysDicService.selectRuleByCode(StoreActivityEnum.MB003.getDicCode());
            } else if (req.getPosterPicName().equals(StoreActivityEnum.MB004.getDicValue())) {
                posterPicCodeResp = sysDicService.selectRuleByCode(StoreActivityEnum.MB004.getDicCode());
            }
            if (!ObjectUtils.isEmpty(posterPicCodeResp)) {
                saveRule(actId, posterPicCodeResp, null, null);
            }
        }

    }

    @Token
    @Log
    @GetMapping("/activityAuditRecordPage")
    @ApiOperation("营销活动审核记录")
    //@Auth(bizType = Auth.OPERATOR)
    public ResponseData<PageInfo<ActActivityAuditRecordResp>> findActivityAuditRecordPage(ActActivityAuditRecordReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        return mtActivityService.findActivityAuditRecordPage(req);
    }

    @Token
    @Log
    @PostMapping("/activityBseInfoInsert")
    @ApiOperation("新增门店活动模版")
    public ResponseData insertActivityBaseInfo(@RequestBody MtActivityBaseInfoInsertReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long loginInfoId = Long.parseLong(getAttribute());
        String loginName = getLoginName();
        return mtActivityService.inserActivityBaseInfo(req, loginInfoId, loginName);
    }

    @Token
    @Log
    @PostMapping("/activityBseInfoUpdate")
    @ApiOperation("修改门店活动模版")
    public ResponseData updateActivityBaseInfo(@RequestBody MtActivityBaseInfoUpdateReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long loginInfoId = Long.parseLong(getAttribute());
        String loginName = getLoginName();
        return mtActivityService.updateActivityBaseInfo(req, loginInfoId, loginName);
    }

    @Token
    @Log
    @PostMapping("/activityBseInfoDel")
    @ApiOperation("删除门店活动模版")
    public ResponseData delActivityBaseInfo(@RequestBody DelReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        return mtActivityService.delActivityBaseInfo(req.getId());
    }

    @Token
    @Log
    @GetMapping("/activityBseInfoPage")
    @ApiOperation("门店活动模版列表")
    public ResponseData<PageInfo<MtActivityBaseInfoPageResp>> delActivityBaseInfo(MtActivityBaseInfoFindReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        return mtActivityService.findActivityBaseInfoPage(req);
    }


    @Token
    @Log
    @GetMapping("/mtList")
    @ApiOperation("门店活动列表-轮播图选择使用")
    //@Auth(bizType = Auth.OPERATOR)
    public ResponseData<List<MtActivityBannerResp>> mtList(MtActivityBannerReq req) {
        return mtActivityService.findMtActivityBanner(req);
    }


    private void saveBusiness(Byte type, Long actId, String activityName, List<String> reqs) {
        if (type == 2) {
            mtActivityService.deleteByActId(actId);
        }
        MtActivityRuleBusiness business = new MtActivityRuleBusiness();
        business.setActId(actId);
        business.setActName(activityName);
        for (String image : reqs) {
            business.setBizValue(image);
            mtActivityService.insertBusiness(business);
        }
    }

    private List<Long> getAgentIds(List<Long> areaIds, List<Long> agentIds) {
        RegionTreeReq treeReq = new RegionTreeReq();
        treeReq.setAreaIds(areaIds);
        List<Long> agentId = sysCompanyAreaService.agentIds(treeReq);
        agentId.addAll(agentIds);
        //去重
        Set<Long> set = new HashSet<>(agentId);
        agentId.clear();
        agentId.addAll(set);
        return agentId;
    }

    private void saveRule(Long id, SysDic resp, String expression, String conditionValue) {
        MtActivityRule rule = new MtActivityRule();
        rule.setActId(id);
        rule.setMold(resp.getDicType());
        rule.setConditions(resp.getDicName());
        rule.setConditionValue(conditionValue);
        rule.setExpression(expression);
        rule.setExpressionField(resp.getDicCode());
        mtActivityService.saveMtActivityRule(rule);
    }

    /**
     * @return true可以参加活动
     */
    private boolean cyRule(MtActivityRule rule, Long grade) {
        Map<String, Object> map = new HashMap<>();
        map.put("grade", grade);
        return IKExpressionUtil.executeIs("grade" + rule.getExpression(), map);
    }
}
